import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QSplitter, QWidget, QVBoxLayout,
                             QHBoxLayout, QLabel, QLineEdit, QTreeWidget, QTreeWidgetItem,
                             QTabWidget, QPushButton, QTextEdit, QFrame, QListWidget,
                             QListWidgetItem, QGroupBox, QFormLayout, QMenu, QAction,
                             QGraphicsDropShadowEffect, QSizePolicy, QScrollArea, QTableWidget, QTableWidgetItem, QHeaderView)
from PyQt5.QtCore import Qt, QSize, QPoint, pyqtSignal
from PyQt5.QtGui import QFont, QIcon, QPixmap, QColor, QPalette
from PyQt5.QtCore import QThread
from PyQt5.QtCore import QTimer
from 基础配置 import settings
import multiprocessing

class TraderThread(QThread):
    def __init__(self, trader, parent=None):
        super().__init__(parent)
        self.trader = trader
        self.result = False

    def run(self):
        try:
            self.result = self.trader.start()
        except Exception as e:
            print(f"交易线程执行出错: {e}")
            self.result = False

    def get_result(self):
        return self.result

def run_market_monitor(log_queue, trade_cmd_queue):
    from 行情监控 import MarketMonitor
    # 子进程中不直接使用trader对象，而是通过队列接收交易指令
    monitor = MarketMonitor(trader=None, log_callback=lambda msg: log_queue.put(msg), trade_cmd_queue=trade_cmd_queue)
    monitor.start()

##header
class CustomTitleBar(QWidget):
    def __init__(self, parent):
        super().__init__(parent)
        self.parent = parent
        self.trader = None  # 添加交易类实例变量
        self.primary_color = "#353071"
        self.initUI()

    def initUI(self):
        # 确保标题栏填充整个宽度
        self.setAttribute(Qt.WA_StyledBackground)  # 确保样式应用到整个组件
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.setStyleSheet(f"""
            background-color: {self.primary_color};
            color: white;
            padding: 10px 10px;
            max-height:50px;
            border-top-left-radius: 20px;
            border-top-right-radius: 20px;
            border-bottom-right-radius: 0px;
            border-bottom-left-radius: 0px;
        """)

        layout = QHBoxLayout(self)
        layout.setContentsMargins(10, 5, 10, 5)  # 调整边距确保按钮不会太靠边
        layout.setSpacing(15)

        # 应用图标和标题
        self.icon = QLabel()
        # 加载本地图片 - 替换为你的实际图片路径
        icon_pixmap = QPixmap("../组件/assets/tb.png")  # 可以是PNG、JPG等格式
        # 缩放图标到合适大小
        self.icon.setPixmap(icon_pixmap.scaled(120, 200, Qt.KeepAspectRatio, Qt.SmoothTransformation))
        self.title = QLabel("股票交易系统")

        # 窗口控制按钮
        self.min_btn = QPushButton("—")
        self.max_btn = QPushButton("□")
        self.close_btn = QPushButton("×")

        # 设置按钮样式
        btn_style = """
            QPushButton {
                background: transparent;
                color: #fff;
                border: none;
                font-size: 18px;
                width: 20px;
                height: 20px;
            }
            QPushButton:hover { 
                background: #fff;
                border-radius: 4px;
                color: #000;
            }
            QPushButton#close_btn:hover {
                background: #e53e3e;
                color: #fff;
                border-radius: 4px;
            }
        """
        self.min_btn.setStyleSheet(btn_style)
        self.max_btn.setStyleSheet(btn_style)
        self.close_btn.setStyleSheet(btn_style)
        self.close_btn.setObjectName("close_btn")

        # 连接按钮信号
        self.min_btn.clicked.connect(self.parent.showMinimized)
        self.max_btn.clicked.connect(self.toggle_maximize)
        self.close_btn.clicked.connect(self.parent.close)

        # 添加到布局
        layout.addWidget(self.icon)
        layout.addStretch()  # 这将把按钮推到最右边
        layout.addWidget(self.min_btn)
        # layout.addWidget(self.max_btn)
        layout.addWidget(self.close_btn)

    def toggle_maximize(self):
        if self.parent.isMaximized():
            self.parent.showNormal()
            self.max_btn.setText("□")
        else:
            self.parent.showMaximized()
            self.max_btn.setText("❐")

    def mouseDoubleClickEvent(self, event):
        self.toggle_maximize()
        event.accept()

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.parent.drag_pos = event.globalPos()
            event.accept()

    def mouseMoveEvent(self, event):
        if event.buttons() == Qt.LeftButton and hasattr(self.parent, 'drag_pos'):
            self.parent.move(self.parent.pos() + event.globalPos() - self.parent.drag_pos)
            self.parent.drag_pos = event.globalPos()
            event.accept()


##body
class QyhtThinkUI(QMainWindow):
    status_changed = pyqtSignal(bool)

    def __init__(self, trader=None,market_monitor=None, parent=None):
        super().__init__(parent)
        self.primary_color = "#353071"
        self.second_color = "#c2c2c2"
        self.trader = trader  # 正确赋值交易实例
        self.market_monitor = market_monitor
        self.market_log_queue = multiprocessing.Queue()
        self.trade_cmd_queue = multiprocessing.Queue()
        if self.market_monitor:
            # 若后续使用线程模式，可改回直接回调；此处使用队列统一到主线程消费
            self.market_monitor.log_callback = lambda msg: self.market_log_queue.put(msg)
            # 注入交易指令队列
            if hasattr(self.market_monitor, 'trade_cmd_queue'):
                self.market_monitor.trade_cmd_queue = self.trade_cmd_queue
        self.is_running = False  # 添加运行状态标志
        self.market_monitoring = False  # 初始未监控
        # 初始化订单数据
        self.filled_orders_sorted = []  # 成交订单
        self.no_filled_orders = []      # 未成交订单
        self.stocks = []
        
        # 移除默认标题栏并设置窗口属性
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)  # 启用透明背景以实现圆角效果
        # 确保信号连接正确
        self.status_changed.connect(self.update_status_ui)
        if self.trader:
            self.trader.set_log_callback(lambda msg: self.market_log_queue.put(msg))
        self.initUI()
        self.append_log(f"指示灯连接状态:{self.receivers(self.status_changed) > 0}")
        # 启动日志轮询定时器（统一从队列取日志，避免跨线程直接操作UI）
        self.market_log_timer = QTimer(self)
        self.market_log_timer.timeout.connect(self.poll_market_log)
        self.market_log_timer.start(1000)
        # 启动交易指令轮询
        self.trade_cmd_timer = QTimer(self)
        self.trade_cmd_timer.timeout.connect(self.poll_trade_cmd)
        self.trade_cmd_timer.start(500)
        # 订单数据自动刷新定时器
        self.orders_refresh_timer = QTimer(self)
        self.orders_refresh_timer.timeout.connect(self.auto_refresh_orders)
        self.orders_refresh_timer.start(1000)  # 5秒自动刷新一次订单数据
        
        # 内存监控定时器
        self.memory_monitor_timer = QTimer(self)
        self.memory_monitor_timer.timeout.connect(self.monitor_memory_usage)
        self.memory_monitor_timer.start(30000)  # 30秒监控一次内存使用

    # 设置窗口基本属性
    def initUI(self):
        self.setWindowTitle('股票交易系统')
        self.setGeometry(100, 100, 1400, 850)

        # 创建主容器，用于实现圆角和阴影效果
        self.main_container = QWidget()
        self.main_container.setStyleSheet(f"""
            QWidget#main_container {{
                background-color: #353071;
                border-radius: 20px;
            }}
        """)
        self.main_container.setObjectName("main_container")

        # 添加阴影效果 - 这里修正了错误
        self.effect = QGraphicsDropShadowEffect()  # 直接使用导入的类
        self.effect.setBlurRadius(20)
        self.effect.setColor(QColor(0, 0, 0, 150))
        self.effect.setOffset(0, 0)
        self.main_container.setGraphicsEffect(self.effect)
        main_layout = QVBoxLayout(self.main_container)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)
        # 添加自定义标题栏
        self.title_bar = CustomTitleBar(self)
        main_layout.addWidget(self.title_bar)
        # 创建主内容
        content_widget = QWidget()
        content_widget.setStyleSheet(f"""
            QWidget#main_body {{
                border-radius: 20px;
                background-color: #efefef;
                margin:10px 20px 20px 20px;
            }}
        """)
        content_widget.setObjectName("main_body")
        content_layout = QHBoxLayout(content_widget)
        content_layout.setContentsMargins(10, 10, 10, 10)
        content_layout.setSpacing(0)
        # 创建分割器，用于左右布局
        splitter = QSplitter(Qt.Horizontal)
        # 添加左侧导航区
        self.left_nav = self.create_left_nav()
        splitter.addWidget(self.left_nav)
        # 添加右侧主操作区
        self.main_content = self.create_main_content()
        splitter.addWidget(self.main_content)
        # 设置分割器初始大小
        splitter.setSizes([140, 1240])
        content_layout.addWidget(splitter)
        main_layout.addWidget(content_widget)
        self.setCentralWidget(self.main_container)
    # 左侧导航区域
    def create_left_nav(self):
        widget = QWidget()
 
        widget.setStyleSheet(f"""
            QWidget{{
                border:0;
            }}
            QWidget#left_nav {{
                background-color: white;
                border-bottom-left-radius: 20px;
                border-top-left-radius: 20px;
                margin:0 0 10px 10px;
                border:0;
            }}
        """)
        widget.setObjectName("left_nav")
        layout = QVBoxLayout(widget)
        layout.setContentsMargins(15, 15, 15, 15)
        layout.setSpacing(15)

        # 顶部标识
        title_label = QLabel('QMT实盘')
        title_font = QFont()
        title_font.setPointSize(14)
        title_font.setBold(True)
        title_label.setFont(title_font)
        title_label.setAlignment(Qt.AlignCenter)
        title_label.setStyleSheet(f"color: {self.primary_color}; margin: 10px 0px;")
        layout.addWidget(title_label)

        # 状态指示灯
        self.status_indicator = QLabel()
        self.status_indicator.setFixedSize(20, 20)
        self.status_indicator.setStyleSheet("""
            background-color: #e53e3e;
            border-radius: 50%;
        """)
        status_layout = QHBoxLayout()
        status_layout.addStretch()
        status_layout.addWidget(QLabel("状态:"))
        status_layout.addWidget(self.status_indicator)
        status_layout.addStretch()
        layout.addLayout(status_layout)

        # 快捷功能区
        shortcut_group = QGroupBox()
        shortcut_layout = QVBoxLayout()
        shortcut_layout.setSpacing(8)


        # 创建快捷按钮
        def create_action_button(text, icon_path=None, icon_size=(24, 24)):
            btn = QPushButton(text)
            btn.setStyleSheet(f"""
                QPushButton {{
                    text-align: left;
                    padding: 10px 15px;
                    border-radius: 6px;
                    background-color: {self.primary_color};
                    color: white;
                }}
                QPushButton:hover {{
                    background-color: {self.second_color};
                }}
            """)
            if icon_path:
                # 方法1: 直接使用图片文件路径
                if isinstance(icon_path, str):
                    icon = QIcon(icon_path)
                # 方法2: 使用QPixmap对象
                elif isinstance(icon_path, QPixmap):
                    icon = QIcon(icon_path)
                # 方法3: 使用QIcon对象
                elif isinstance(icon_path, QIcon):
                    icon = icon_path
                else:
                    icon = QIcon()
                
                btn.setIcon(icon)
                btn.setIconSize(QSize(*icon_size))
            return btn


        self.monitor_btn = create_action_button("连接QMT", "../组件/assets/MEGAsync_v2.ico", (40, 40))
        self.monitor_btn.clicked.connect(self.toggle_trader)
        
        self.rb_btn = create_action_button("行情监控", "../组件/assets/SeratoDJ_v2", (40, 40))
        self.rb_btn.clicked.connect(self.toggle_market_monitor)

        settings_btn = create_action_button("订单监控",  "../组件/assets/transmission_v5.ico", (40, 40))
        help_btn = create_action_button("订单同步",  "../组件/assets/iconverticons.ico", (40, 40))
        help_btn.clicked.connect(self.upload_order)

        shortcut_layout.addWidget(self.monitor_btn)
        shortcut_layout.addWidget(self.rb_btn)
        shortcut_layout.addWidget(settings_btn)
        shortcut_layout.addWidget(help_btn)

        shortcut_layout.addStretch()
        shortcut_group.setLayout(shortcut_layout)
        layout.addWidget(shortcut_group)

        layout.addStretch()

        # 底部用户信息
        user_widget = QWidget()
        user_layout = QHBoxLayout(user_widget)
        user_layout.setContentsMargins(10, 10, 10, 10)
        user_layout.setSpacing(10)

        # 用户头像
        avatar = QLabel()
        avatar.setFixedSize(32, 32)
        avatar.setStyleSheet(f"""
            background-color: {self.primary_color};
            border-radius: 16px;
            color: white;
            font-weight: bold;
            qproperty-alignment: 'AlignCenter';
        """)
        avatar.setText("Y")

        # 用户信息
        user_info = QWidget()
        user_info_layout = QVBoxLayout(user_info)
        user_info_layout.setContentsMargins(0, 0, 0, 0)
        user_info_layout.setSpacing(2)

        user_name = QLabel(f"账户:{settings.ACC}")


        user_role = QLabel("账户:5788")
        user_role.setStyleSheet("color: #6c757d; font-size: 11px;")

        user_info_layout.addWidget(user_name)
        # user_info_layout.addWidget(user_role)

        user_layout.addWidget(avatar)
        user_layout.addWidget(user_info)

        layout.addWidget(user_widget)

        return widget
    #更新UI
    def update_status_ui(self, is_running):
        print(f"update_status_ui 被调用，状态: {'运行' if is_running else '停止'}")  # 必须输出
        self.is_running = is_running
        
        # 确保状态与实际运行状态一致
        if self.trader:
            actual_running = self.trader.is_running()
            if actual_running != is_running:
                print(f"状态不一致，实际状态: {actual_running}, UI状态: {is_running}")
                is_running = actual_running
                self.is_running = actual_running
        
        if is_running:
            print("更新UI为运行状态")
            self.monitor_btn.setText("断开连接")
            self.status_indicator.setStyleSheet("background-color: #38a169; border-radius: 10px;")
        else:
            print("更新UI为停止状态")
            self.monitor_btn.setText("连接QMT")
            self.status_indicator.setStyleSheet("background-color: #e53e3e; border-radius: 10px;")
        # 强制刷新
        self.monitor_btn.repaint()
        self.status_indicator.repaint()
    # 启动/关闭QMT
    def toggle_trader(self):
        if not self.trader:
            self.status_changed.emit(False)
            return

        if not self.is_running:
            # 启动交易
            self.thread = TraderThread(self.trader)
            self.thread.finished.connect(self.on_trader_thread_finished)
            self.thread.start()
        else:
            # 停止交易
            self.trader.stop()
            self.status_changed.emit(False)
    #监控启动完成回调
    def toggle_market_monitor(self):
        if not hasattr(self, '_market_monitor_process') or not self._market_monitor_process.is_alive():
            self.market_monitoring = True
            # 检查trader是否可用
            if not self.trader or not self.trader.is_running():
                self.append_log("❌ 交易系统未启动，无法启动行情监控")
                self.rb_btn.setText("行情监控")
                self.market_monitoring = False
                return
                
            self._market_monitor_process = multiprocessing.Process(
                target=run_market_monitor,
                args=(self.market_log_queue, self.trade_cmd_queue)
            )
            self._market_monitor_process.start()
            self.append_log("行情监控已启动（子进程）")
            self.rb_btn.setText("监控中")
        else:
            self.market_monitoring = False
            self._market_monitor_process.terminate()
            self.rb_btn.setText("行情监控")
            self.append_log("行情监控已请求停止")
    #qmt启动完成回调
    def on_trader_thread_finished(self):
        """交易线程完成回调"""
        if hasattr(self, 'thread'):
            success = self.thread.get_result()
            if success:
                self.status_changed.emit(True)
            else:
                self.status_changed.emit(False)
            self.thread.deleteLater()
    # 右侧主操作区域"
    def create_main_content(self):
        widget = QWidget()
        layout = QVBoxLayout(widget)
        layout.setContentsMargins(0, 20, 20, 20)
        layout.setSpacing(20)

        # 顶部操作栏
        top_bar = QWidget()
        top_bar.setStyleSheet("""
            background: qlineargradient(x1:0, y1:0, x2:1, y2:0, 
                stop:0 #667eea, stop:1 #764ba2);
            border-radius: 12px; 
            padding: 15px;
            margin-bottom: 10px;
        """)
        top_layout = QHBoxLayout(top_bar)
        top_layout.setContentsMargins(20, 10, 20, 10)
        top_layout.addStretch()

        # tab选项卡样式
        self.tab_widget = QTabWidget()
        self.tab_widget.setStyleSheet(f"""
            QTabWidget::pane {{
                border: none;
                background-color: transparent;
                margin-top: 5px;
            }}
            QTabWidget::tab-bar {{
                alignment: left;
            }}
            QTabBar::tab {{
                background: {self.second_color};
                color: #fff;
                padding: 12px 24px;
                margin-right: 8px;
                border: 2px solid transparent;
                border-top-left-radius: 12px;
                border-top-right-radius: 12px;
                font-size: 30px;
                min-width: 120px;
                min-height:40px;
            }}
            QTabBar::tab:hover {{
                background: {self.primary_color};
                color: white;
            }}
            QTabBar::tab:selected {{
                background: {self.primary_color};
                color: white;
            }}
 
        """)

        

        # 列表1标签页
        list1_tab = self.create_list_tab("当前挂单")
        self.tab_widget.addTab(list1_tab, "当前挂单")

        # 列表2标签页
        list2_tab = self.create_list_tab("成交记录")
        self.tab_widget.addTab(list2_tab, "成交记录")

        # 实时行情
        list0_tab = self.create_stock()
        self.tab_widget.addTab(list0_tab, "实时行情")



        layout.addWidget(self.tab_widget)

        # 日志
        code_group = QGroupBox("运行日志")
        code_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid #e2e8f0;
                border-radius: 12px;
                margin-top: 15px;
                font-weight: 600;
                color: #374151;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 15px;
                padding: 0 8px;
                color: #374151;
                font-size: 16px;
            }
        """)
        code_layout = QVBoxLayout()

        self.code_editor = QTextEdit()
        self.code_editor.setReadOnly(True)
        self.code_editor.setStyleSheet("""
            QTextEdit {
                background-color: #f8fafc;
                color: #1f2937;
                border-radius: 8px;
                padding: 15px; 
                font-family: 'Consolas', 'Monaco', '微软雅黑';
                font-size:20px;
                border: 1px solid #e2e8f0;
            }
            QScrollBar:vertical {
                background: #f1f5f9;
                width: 8px;
                margin: 0px;
                border-radius: 4px;
            }
            QScrollBar::handle:vertical {
                background: #cbd5e1;
                min-height: 20px;
                border-radius: 4px;
            }
            QScrollBar::handle:vertical:hover {
                background: #94a3b8;
            }
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                height: 0px;
                background: none;
                border: none;
            }
            QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
                background: none;
            }
        """)

        code_layout.addWidget(self.code_editor)
        code_group.setLayout(code_layout)

        # 设置代码区高度
        code_group.setMaximumHeight(300)
        layout.addWidget(code_group)

        return widget

    ##创建实时行情
    def create_stock(self):
        widget = QWidget()
        layout = QVBoxLayout(widget)
        layout.setContentsMargins(10, 10, 10, 10)
        layout.setSpacing(10)

 

        # 创建股票列表表格
        self.stock_table = QTableWidget()
        self.stock_table.setColumnCount(9)
        self.stock_table.setHorizontalHeaderLabels(["股票名称", "当前价格", "状态", "持续时间","MACD","RSI", "更新时间", "市价买", "市价卖"])
        
        # 设置表格样式
        self.stock_table.setStyleSheet("""
            QTableWidget {
                background-color: white;
                font-size: 20px;
                border-radius: 8px;
                gridline-color: #f3f4f6;
                selection-background-color: #353071;
                selection-color: white;
                height: 50px;
            }
            QTableWidget::item {
                padding: 1px;
                font-size: 20px;
                height: 50px;
            }
            QTableWidget::item:selected {
                color: white;
                height: 50px;
            }
            QHeaderView::section {
                background-color: #353071;
                color: #fff;
                border: none;
                font-size: 20px;
                font-weight: bold;
            }
 
        """)
        
        # 设置列宽
        header = self.stock_table.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.Stretch)  # 股票名称列自适应
        header.setSectionResizeMode(1, QHeaderView.Fixed)    # 当前价格列固定宽度
        header.setSectionResizeMode(2, QHeaderView.Fixed)    # 股票状态列固定宽度
        header.setSectionResizeMode(3, QHeaderView.Fixed)    # 持续时间列固定宽度
        header.setSectionResizeMode(4, QHeaderView.Fixed)  # 更新时间列固定宽度
        header.setSectionResizeMode(5, QHeaderView.Fixed)  # 操作列固定宽度
        header.setSectionResizeMode(6, QHeaderView.Fixed)  # 操作列固定宽度
        header.setSectionResizeMode(7, QHeaderView.Fixed)  # 操作列固定宽度

        
        self.stock_table.setColumnWidth(1, 100)  # 当前价格列宽
        self.stock_table.setColumnWidth(2, 100)  # 股票状态列宽
        self.stock_table.setColumnWidth(3, 120)  # 持续时间列宽
        self.stock_table.setColumnWidth(4, 100)  # 持续时间列宽
        self.stock_table.setColumnWidth(5, 100)  # 持续时间列宽
        self.stock_table.setColumnWidth(6, 160)  # 更新时间列固定宽度
        self.stock_table.setColumnWidth(7, 100)  # 操作列宽
        self.stock_table.setColumnWidth(8, 100)  # 操作列宽


        self.stock_table.verticalHeader().setDefaultSectionSize(30)  
        
        # 隐藏序号列（行号列）
        self.stock_table.verticalHeader().setVisible(False)
        
        # 隐藏滚动条
        self.stock_table.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.stock_table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        
        # 使用self.stocks数据填充表格
        self.update_stock_table()
        
        # 设置表格不可编辑
        self.stock_table.setEditTriggers(QTableWidget.NoEditTriggers)
        
        # 设置表格高度
        self.stock_table.setMaximumHeight(500)
        
        layout.addWidget(self.stock_table)
        
 

        return widget
    
    def update_stock_table(self):
        """更新股票表格数据"""
        if not self.stocks:
            # 如果没有数据，显示空表格
            self.stock_table.setRowCount(0)
            return
            
        self.stock_table.setRowCount(len(self.stocks))
        
        for row, stock in enumerate(self.stocks):
            # 股票名称
            name_item = QTableWidgetItem(stock['name'])
            name_item.setTextAlignment(Qt.AlignCenter)
            self.stock_table.setItem(row, 0, name_item)
            
            # 当前价格
            price_item = QTableWidgetItem(stock['now_price'])
            price_item.setTextAlignment(Qt.AlignCenter)
            self.stock_table.setItem(row, 1, price_item)
            
            # 股票状态 - 根据is_updown字段判断
            is_updown = stock['is_updown']
            if is_updown:
                status = "震荡"
                bg_color = "#dcfce7"  # 浅绿色背景
                fg_color = "#166534"  # 深绿色文字
            else:
                status = "无"
                bg_color = "#f3f4f6"  # 浅灰色背景
                fg_color = "#6b7280"  # 灰色文字
            
            status_item = QTableWidgetItem(status)
            status_item.setTextAlignment(Qt.AlignCenter)
            status_item.setBackground(QColor(bg_color))
            status_item.setForeground(QColor(fg_color))
            self.stock_table.setItem(row, 2, status_item)

            # 持续时间 - 从update_at计算
            try:
                from datetime import datetime
                update_time = datetime.strptime(stock['update_at'], '%Y-%m-%d %H:%M:%S')
                time_str = update_time.strftime('%H:%M:%S')  # 转换成 "时:分:秒" 字符串
            except:
                time_str = "未知"

            if stock['longs']:
                duration_str = f"{stock['longs']}m"
            else:
                duration_str = "-"
            duration_item = QTableWidgetItem(duration_str)
            duration_item.setTextAlignment(Qt.AlignCenter)

            time_item = QTableWidgetItem(time_str)
            time_item.setTextAlignment(Qt.AlignCenter)
            self.stock_table.setItem(row, 3, duration_item)

            macd_item = QTableWidgetItem(stock['macd'])
            macd_item.setTextAlignment(Qt.AlignCenter)
            rs1_item = QTableWidgetItem(f"{int(float(stock['rs1']))}")  # 直接截断小数部分（44.48 → 44）
            rs1_item.setTextAlignment(Qt.AlignCenter)
            self.stock_table.setItem(row, 4, macd_item)
            self.stock_table.setItem(row, 5, rs1_item)
            self.stock_table.setItem(row, 6, time_item)

            # 操作列 - 市价买入按钮
            try:
                action_btn = QPushButton("买")
                action_btn.setStyleSheet(f"""
                    QPushButton {{
                        background: green;
                        color: white;
                        border: none;
                        font-size: 20px; 
                    }}
                    QPushButton:hover {{
                        background: {self.second_color};
                    }}
                """)
                action_btn.clicked.connect(lambda _=False, code=stock['stock_code']: self.on_market_buy_clicked(code))
                self.stock_table.setCellWidget(row, 7, action_btn)
            except Exception:
                pass

            try:
                action_btn2 = QPushButton("卖")
                action_btn2.setStyleSheet(f"""
                    QPushButton {{
                        background: red;
                        color: white;
                        border: none;
                        font-size: 20px; 
                    }}
                    QPushButton:hover {{
                        background: {self.second_color};
                    }}
                """)
                action_btn2.clicked.connect(lambda _=False, code=stock['stock_code']: self.on_market_sell_clicked(code))
                self.stock_table.setCellWidget(row, 8, action_btn2)
            except Exception:
                pass
    ##创建列表标签页内容
    def create_list_tab(self, tab_name):
        widget = QWidget()
        layout = QVBoxLayout(widget)
        layout.setContentsMargins(10, 10, 10, 10)
        layout.setSpacing(10)

        # 显示订单数量
        if tab_name == "当前挂单":
            orders_data = self.no_filled_orders
            order_type = "未成交"
        else:  # "成交记录"
            orders_data = self.filled_orders_sorted
            order_type = "已成交"

        count_label = QLabel(f"共 {len(orders_data)} 条{order_type}订单")
        count_label.setStyleSheet("""
            color: #6b7280;
            font-size: 20px;
            margin-top: 10px;
        """)
        layout.addWidget(count_label)

        # 创建自定义滚动区域
        scroll_area = self.create_draggable_scroll_area()

        # 横向卡片容器
        cards_container = QWidget()
        cards_layout = QHBoxLayout(cards_container)
        cards_layout.setContentsMargins(0, 20, 0, 0)
        cards_layout.setSpacing(20)
        cards_layout.setAlignment(Qt.AlignLeft)

        # 创建订单卡片
        if orders_data:
            for order in orders_data:
                card = self.create_order_card(order, order_type)
                cards_layout.addWidget(card)
        else:
            empty_widget = self.create_empty_state_widget(order_type)
            cards_layout.addWidget(empty_widget)

        scroll_area.setWidget(cards_container)
        layout.addWidget(scroll_area)

        return widget
    ##创建可拖动的滚动区域
    def create_draggable_scroll_area(self):
        class DraggableScrollArea(QScrollArea):
            def __init__(self, parent=None):
                super().__init__(parent)
                self.setWidgetResizable(True)
                self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
                self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
                self.setStyleSheet("""
                    QScrollArea {
                        border: none;
                        background: transparent;
                    }
                """)
                self.dragging = False
                self.last_pos = None

            def mousePressEvent(self, event):
                if event.button() == Qt.LeftButton:
                    self.dragging = True
                    self.last_pos = event.pos()
                    self.setCursor(Qt.ClosedHandCursor)
                super().mousePressEvent(event)

            def mouseMoveEvent(self, event):
                if self.dragging and self.last_pos:
                    delta = event.pos() - self.last_pos
                    h_bar = self.horizontalScrollBar()
                    h_bar.setValue(h_bar.value() - delta.x())
                    self.last_pos = event.pos()
                super().mouseMoveEvent(event)

            def mouseReleaseEvent(self, event):
                if event.button() == Qt.LeftButton:
                    self.dragging = False
                    self.setCursor(Qt.ArrowCursor)
                super().mouseReleaseEvent(event)

            def wheelEvent(self, event):
                h_bar = self.horizontalScrollBar()
                h_bar.setValue(h_bar.value() - event.angleDelta().y())
                event.accept()
                
            def closeEvent(self, event):
                """重写关闭事件，确保清理资源"""
                try:
                    # 清理滚动区域内的组件
                    widget = self.takeWidget()
                    if widget:
                        widget.deleteLater()
                except:
                    pass
                super().closeEvent(event)
                
        return DraggableScrollArea()
    ##订单卡片
    def create_order_card(self, order, order_type="成交"):
        """创建单个订单卡片"""
        card = QFrame()
        card.setFixedSize(260, 220)
        style = """ color: #1f2937; font-size: 25px; border:0;font-family:  '微软雅黑';"""

        card.setStyleSheet(f"""
            QFrame {{
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 white, stop:1 #f8fafc);
                border-radius: 16px;
                border: 2px solid #e2e8f0;
            }}
            QFrame:hover {{
                border: 2px solid {self.primary_color};
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 white, stop:1 #f1f5f9);
                transform: translateY(-2px);
            }}
        """)
        card_layout = QVBoxLayout(card)
        card_layout.setContentsMargins(20, 20, 20, 20)
        card_layout.setSpacing(15)

        # 顶部信息行
        top_row = QHBoxLayout()
        # 订单ID
        order_id_label = QLabel(f"ID: {order.order_sysid}")
        order_id_label.setStyleSheet(style)

        # 时间信息
        import datetime
        dt = datetime.datetime.fromtimestamp(order.order_time)
        formatted_time = dt.strftime("%H:%M")
        time_label = QLabel(f"{formatted_time}")
        time_label.setStyleSheet(style)

        top_row.addWidget(order_id_label)
        top_row.addStretch()
        top_row.addWidget(time_label)

        # 股票信息行
        stock_info = self.create_stock_info_layout(order, style)

        # 价格和数量信息
        price_volume_layout = self.create_price_volume_layout(order, style)

        # 添加所有组件到卡片
        card_layout.addLayout(top_row)
        card_layout.addLayout(stock_info)
        card_layout.addLayout(price_volume_layout)

        # 添加操作按钮
        self.add_action_button(card_layout, order, order_type)

        return card
    ##提示信息
    def show_confirmation_dialog(self, message):
        """显示自定义确认对话框"""
        from PyQt5.QtWidgets import QMessageBox
        msg_box = QMessageBox()
        msg_box.setWindowTitle("提示信息")
        msg_box.setWindowFlags(Qt.CustomizeWindowHint | Qt.FramelessWindowHint)
        msg_box.setText(message)
        msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        msg_box.setDefaultButton(QMessageBox.No)

        # 设置样式表
        msg_box.setStyleSheet(f"""
            QMessageBox {{
                background-color: #ffffff;
                border-radius: 10px;
                border: 3px solid {self.primary_color};
                padding: 20px;
            }}
            QMessageBox QLabel {{
                color: #333333;
                font-size: 18px;
            }}
            QMessageBox QPushButton {{
                background-color: {self.primary_color};
                color: white;
                border-radius: 8px;
                padding: 8px 16px;
                font-size: 16px;
                min-width: 80px;
            }}
            QMessageBox QPushButton:hover {{
                background-color: {self.primary_color};
            }}
        """)

        # 居中显示
        main_window_rect = self.frameGeometry()
        main_center = main_window_rect.center()
        msg_box_rect = msg_box.frameGeometry()
        msg_box.move(
            main_center.x() - msg_box_rect.width() // 2 + 200,
            main_center.y() - msg_box_rect.height() // 2 +200
        )

        return msg_box.exec_() == QMessageBox.Yes
    ##订单卡片body1
    def create_stock_info_layout(self, order, style):
        """创建股票信息布局"""
        stock_info = QHBoxLayout()

        # 获取股票名称
        stock_name = "未知股票"
        if hasattr(self.trader, 'callback') and hasattr(self.trader.callback, 'stock_type'):
            stock_name = self.trader.callback.stock_type.get(order.stock_code, order.stock_code)

        stock_label = QLabel(f"{stock_name}")
        stock_label.setStyleSheet(style)

        # 交易方向
        direction_text = "买入" if order.order_type == 23 else "卖出"
        direction_color = "green" if order.order_type == 23 else "red"
        direction_label = QLabel(direction_text)
        direction_label.setStyleSheet(f"""
            color: #fff;
            font-size: 20px;
            font-family:  '微软雅黑';
            padding: 4px 8px;
            background: {direction_color};
            border-radius: 4px;
            border:0px;
        """)

        stock_info.addWidget(stock_label)
        stock_info.addStretch()
        stock_info.addWidget(direction_label)

        return stock_info
    ##订单卡片body2
    def create_price_volume_layout(self, order, style):
        """创建价格和数量布局"""
        price_volume_layout = QHBoxLayout()

        # 价格信息
        if hasattr(order, 'traded_price') and order.traded_price:
            price_text = f"¥{order.traded_price}"
        else:
            price_text = f"¥{order.price}"

        price_label = QLabel(price_text)
        price_label.setStyleSheet(style)

        # 数量信息
        if hasattr(order, 'traded_volume') and order.traded_volume:
            volume_text = f"{order.traded_volume / 10000}万股"
        else:
            volume_text = f"{order.order_volume / 10000}万股"

        volume_label = QLabel(volume_text)
        volume_label.setStyleSheet(style)
        price_volume_layout.addWidget(price_label)
        price_volume_layout.addStretch()
        price_volume_layout.addWidget(volume_label)

        return price_volume_layout
    ##订单卡片按钮
    def add_action_button(self, card_layout, order, order_type):
        """添加操作按钮到卡片"""
        if order_type == "未成交":
            action_btn = QPushButton("撤单")
            action_btn.setStyleSheet(f"""
                            QPushButton {{
                                background: {self.primary_color};
                                color: white;
                                border: none;
                                border-radius: 8px;
                                padding: 8px 16px;
                                font-size: 20px; 
                                width:100px;
                                height:50px;
                            }}
                            QPushButton:hover {{
                                background: {self.primary_color};
                            }}
                        """)

            # action_btn.clicked.connect(lambda: self.cancel_order(order.order_sysid))

            # 添加确认对话框
            def on_cancel_clicked():
                if self.show_confirmation_dialog(f"确定要撤销订单 {order.order_sysid} 吗？"):
                    self.cancel_order(order.order_sysid)

            action_btn.clicked.connect(on_cancel_clicked)

            action_btn_give_up = QPushButton("平仓")
            action_btn_give_up.setStyleSheet(f"""
                            QPushButton {{
                                background: red;
                                color: white;
                                border: none;
                                border-radius: 8px;
                                padding: 8px 16px;
                                font-size: 20px; 
                                width:100px;
                                height:50px;
                            }}
                            QPushButton:hover {{
                                background: {self.primary_color};
                            }}
                        """)

            # 添加确认对话框
            def on_give_up_clicked():
                if self.show_confirmation_dialog(f"确定要平仓订单 {order.order_sysid} 吗？"):
                    self.give_up_order(order.order_sysid)

            action_btn_give_up.clicked.connect(on_give_up_clicked)
            
            # 创建水平布局容器来放置两个按钮
            button_layout = QHBoxLayout()
            button_layout.addWidget(action_btn)
            button_layout.addWidget(action_btn_give_up)
            button_layout.setSpacing(10)  # 设置按钮间距
            
            # 将水平布局添加到主卡片布局
            card_layout.addLayout(button_layout)


        else:
            action_btn_success = QPushButton("已经成交")
            action_btn_success.setStyleSheet(f"""
                QPushButton {{
                    background: {self.primary_color};
                    color: white;
                    border: none;
                    border-radius: 8px;
                    padding: 8px 16px;
                    font-size: 20px; 
                }}
                QPushButton:hover {{
                    background: {self.primary_color};
                }}
            """)
            card_layout.addWidget(action_btn_success)
    ##订单卡片空状态
    def create_empty_state_widget(self, order_type):
        """创建空状态组件"""
        empty_widget = QWidget()
        empty_layout = QVBoxLayout(empty_widget)
        empty_layout.setAlignment(Qt.AlignCenter)

        empty_icon = QLabel()
        icon_pixmap = QPixmap("../组件/assets/no.png")
        empty_icon.setPixmap(icon_pixmap.scaled(100, 100, Qt.KeepAspectRatio, Qt.SmoothTransformation))
        empty_icon.setAlignment(Qt.AlignCenter)
        empty_icon.setStyleSheet("""margin-left:330px;""")

        empty_text = QLabel(f"暂无{order_type}订单")
        empty_text.setStyleSheet("""
            color: #9ca3af;
            font-size: 20px;
            margin-left:330px;
        """)
        empty_text.setAlignment(Qt.AlignCenter)

        empty_layout.addWidget(empty_icon)
        empty_layout.addWidget(empty_text)

        return empty_widget
    #自动刷新订单数据（静默模式）
    def auto_refresh_orders(self):
        try:
            if self.trader and self.trader.is_running():
                # 获取最新数据
                self.filled_orders_sorted, self.no_filled_orders, self.stocks = self.trader.callback.get_orders()
                
                # 更新股票表格
                if hasattr(self, 'stock_table'):
                    self.update_stock_table()

                # 只更新当前显示的标签页内容，不重建整个标签页
                current_tab = self.tab_widget.currentIndex()
                if current_tab == 0:  # 当前挂单
                    self.update_orders_tab_content("当前挂单")
                elif current_tab == 1:  # 成交记录
                    self.update_orders_tab_content("成交记录")
                # 实时行情标签页不需要更新，因为股票表格已经更新了
                ##订单监控
                self.trader.callback.look_orders()

        except Exception as e:
            pass
            # self.append_log(f"[自动刷新] 错误: {str(e)}")
    
    def update_orders_tab_content(self, tab_name):
        """更新订单标签页内容，避免重建整个标签页"""
        try:
            current_widget = self.tab_widget.currentWidget()
            if not current_widget:
                return
                
            # 保存当前滚动位置
            scroll_area = current_widget.findChild(QScrollArea)
            scroll_pos = scroll_area.horizontalScrollBar().value() if scroll_area else 0
            
            # 获取数据
            if tab_name == "当前挂单":
                orders_data = self.no_filled_orders
                order_type = "未成交"
            else:  # "成交记录"
                orders_data = self.filled_orders_sorted
                order_type = "已成交"
            
            # 更新订单数量标签
            count_label = current_widget.findChild(QLabel)
            if count_label:
                count_label.setText(f"共 {len(orders_data)} 条{order_type}订单")
            
            # 更新滚动区域内容
            if scroll_area:
                # 清理旧的卡片容器
                old_container = scroll_area.takeWidget()
                if old_container:
                    old_container.deleteLater()
                
                # 创建新的卡片容器
                cards_container = QWidget()
                cards_layout = QHBoxLayout(cards_container)
                cards_layout.setContentsMargins(0, 20, 0, 0)
                cards_layout.setSpacing(20)
                cards_layout.setAlignment(Qt.AlignLeft)
                
                # 创建订单卡片
                if orders_data:
                    for order in orders_data:
                        card = self.create_order_card(order, order_type)
                        cards_layout.addWidget(card)
                else:
                    empty_widget = self.create_empty_state_widget(order_type)
                    cards_layout.addWidget(empty_widget)
                
                scroll_area.setWidget(cards_container)
                
                # 恢复滚动位置
                scroll_area.horizontalScrollBar().setValue(scroll_pos)
                
        except Exception as e:
            self.append_log(f"[更新标签页内容] 错误: {str(e)}")
    #添加日志
    def append_log(self, text):
        # 获取当前时间（时分格式）
        from datetime import datetime
        timestamp = datetime.now().strftime("%H:%M")

        # 在文本前添加时间戳
        text_with_time = f"[{timestamp}] {text}"

        # 限制日志长度，避免内存过多
        max_lines = 1000  # 最多保留1000行日志
        old = self.code_editor.toPlainText()
        lines = old.split('\n') if old else []

        # 如果行数超过限制，删除前面的行
        if len(lines) > max_lines:
            lines = lines[-max_lines:]

        # 添加新日志
        lines.append(text_with_time)
        new = '\n'.join(lines)

        self.code_editor.setPlainText(new)
        self.code_editor.moveCursor(self.code_editor.textCursor().End)
    #监控日志
    def poll_market_log(self):
        while not self.market_log_queue.empty():
            msg = self.market_log_queue.get()
            self.append_log(f"[行情监控] {msg}")

    def poll_trade_cmd(self):
        try:
            while not self.trade_cmd_queue.empty():
                cmd = self.trade_cmd_queue.get()
                if not (self.trader and self.trader.is_running() and hasattr(self.trader, 'callback')):
                    self.append_log("[交易] 未连接QMT，忽略交易指令")
                    continue
                action = cmd.get("action")
                code = cmd.get("code")
                price = cmd.get("price")
                volume = int(cmd.get("volume", 100))
                reason = cmd.get("reason", "")
                if action == "buy":
                    from xtquant import xtconstant
                    # 使用市价单进行买入，更适合MACD金叉自动买入
                    order_id = self.trader.callback.place_market_order(
                        stock_code=code,
                        volume=volume,
                        direction=xtconstant.STOCK_BUY,
                        order_remark=reason or "策略买入"
                    )
                    if order_id:
                        self.append_log(f"[交易] MACD金叉自动买入成功: {code}，数量 {volume}，委托ID: {order_id}")
                    else:
                        self.append_log(f"[交易] MACD金叉自动买入失败: {code}")
                elif action == "sell":
                    from xtquant import xtconstant
                    self.trader.callback.place_reverse_order(
                        stock_code=code,
                        price=price,
                        volume=volume,
                        direction=xtconstant.STOCK_SELL,
                        order_remark=reason or "策略卖出"
                    )
                elif action == "close_by_code":
                    # 调用按代码平仓（将相关卖单改为市价以尽快成交）
                    self.give_up_order_by_code(code)
                    self.append_log(f"[交易] MACD死叉自动平仓: {code}")
                else:
                    self.append_log(f"[交易] 未知指令: {cmd}")
        except Exception as e:
            self.append_log(f"[交易] 处理交易指令失败: {e}")
    #取消订单
    def cancel_order(self, order_id):
        if self.trader and self.trader.is_running():
            self.trader.callback.cancel_order(order_id)
        else:
            self.append_log("请先连接QMT")
    #平仓
    def give_up_order(self, order_id):
        if self.trader and self.trader.is_running():
            self.trader.callback.modify_to_market_order(order_id)
        else:
            self.append_log("请先连接QMT")
    #按照股票代码平仓
    def give_up_order_by_code(self, stock_code):
        if self.trader and self.trader.is_running():
            self.trader.callback.cancel_all_sell_orders(stock_code)
        else:
            self.append_log("请先连接QMT")
    #市价买入
    def on_market_buy_clicked(self, stock_code):

        code_to_volume = {s["all_code"]: s["volume"] for s in settings.STOCK_CODE}
        volume = int(code_to_volume.get(stock_code, 100))
        code_to_name = {s["all_code"]: s["name"] for s in settings.STOCK_CODE}
        stock_name = code_to_name.get(stock_code, "名称")

        try:
            if not (self.trader and self.trader.is_running() and hasattr(self.trader, 'callback')):
                self.append_log("请先连接QMT")
                return
            if not self.show_confirmation_dialog(f"是否市价买入 {stock_name} : {volume}股？"):
                return
            from xtquant import xtconstant
            # 获取默认下单数量
            order_id = self.trader.callback.place_market_order(
                stock_code=stock_code,
                volume=volume,
                direction=xtconstant.STOCK_BUY,
                order_remark="市价"
            )
            if order_id:
                self.append_log(f"[交易] 市价买入已提交 {stock_code}，数量 {volume}，委托ID: {order_id}")
            else:
                self.append_log(f"[交易] 市价买入提交失败 {stock_code}")
        except Exception as e:
            self.append_log(f"[交易] 市价买入异常: {e}")

    # 市价卖出
    def on_market_sell_clicked(self, stock_code):

        code_to_volume = {s["all_code"]: s["volume"] for s in settings.STOCK_CODE}
        volume = int(code_to_volume.get(stock_code, 100))
        code_to_name = {s["all_code"]: s["name"] for s in settings.STOCK_CODE}
        stock_name = code_to_name.get(stock_code, "名称")

        try:
            if not (self.trader and self.trader.is_running() and hasattr(self.trader, 'callback')):
                self.append_log("请先连接QMT")
                return
            if not self.show_confirmation_dialog(f"是否市价卖出 {stock_name} : {volume}股？"):
                return
            from xtquant import xtconstant
            # 获取默认下单数量
            order_id = self.trader.callback.place_market_order(
                stock_code=stock_code,
                volume=volume,
                direction=xtconstant.STOCK_SELL,
                order_remark="市价"
            )
            if order_id:
                self.append_log(f"[交易] 市价卖出已提交 {stock_code}，数量 {volume}，委托ID: {order_id}")
            else:
                self.append_log(f"[交易] 市价卖出提交失败 {stock_code}")
        except Exception as e:
            self.append_log(f"[交易] 市价卖出异常: {e}")
    #同步成交订单
    def upload_order(self):
        """上传订单"""
        if self.trader and self.trader.is_running():
            self.trader.callback.save_orders()
        else:
            self.append_log("请先连接QMT")
    
    ##关闭程序
    def closeEvent(self, event):
        """窗口关闭事件处理"""
        try:
            print("正在关闭应用程序...")
            
            # 停止所有定时器
            if hasattr(self, 'orders_refresh_timer'):
                self.orders_refresh_timer.stop()
                self.orders_refresh_timer.deleteLater()
                
            if hasattr(self, 'market_log_timer'):
                self.market_log_timer.stop()
                self.market_log_timer.deleteLater()
                
            if hasattr(self, 'memory_monitor_timer'):
                self.memory_monitor_timer.stop()
                self.memory_monitor_timer.deleteLater()
            
            # 停止行情监控（线程版本）
            if hasattr(self, '_market_thread') and self._market_thread.isRunning():
                try:
                    if self.market_monitor:
                        self.market_monitor.stop()
                except Exception:
                    pass
                self._market_thread.wait(5000)

            # 兼容旧的子进程版本（若存在则清理）
            if hasattr(self, '_market_monitor_process') and self._market_monitor_process.is_alive():
                self._market_monitor_process.terminate()
                self._market_monitor_process.join(timeout=5)
                if self._market_monitor_process.is_alive():
                    self._market_monitor_process.kill()
                    
            # 清理UI组件
            self.cleanup_ui_components()
                
            # 停止交易系统
            if self.trader and self.trader.is_running():
                print("正在停止交易系统...")
                self.trader.stop()
                
            # 等待交易线程完成
            if hasattr(self, 'thread') and self.thread.isRunning():
                self.thread.wait(5000)  # 等待最多5秒
                if self.thread.isRunning():
                    print("警告: 交易线程未能正常停止")
                    
            # 清理数据
            self.filled_orders_sorted.clear()
            self.no_filled_orders.clear()
            self.stocks.clear()
            
            print("应用程序关闭完成")
            event.accept()
            
        except Exception as e:
            print(f"关闭应用程序时出错: {e}")
            import traceback
            traceback.print_exc()
            event.accept()  # 即使出错也要关闭窗口
    
    def cleanup_ui_components(self):
        """清理UI组件，释放内存"""
        try:
            # 清理标签页内容
            for i in range(self.tab_widget.count()):
                widget = self.tab_widget.widget(i)
                if widget:
                    # 清理滚动区域内的组件
                    scroll_area = widget.findChild(QScrollArea)
                    if scroll_area:
                        container = scroll_area.takeWidget()
                        if container:
                            container.deleteLater()
                    widget.deleteLater()
            
            # 清理日志编辑器
            if hasattr(self, 'code_editor'):
                self.code_editor.clear()
                self.code_editor.deleteLater()
                
        except Exception as e:
            print(f"清理UI组件时出错: {e}")
    
    def monitor_memory_usage(self):
        """监控内存使用情况"""
        try:
            import psutil
            import os
            
            # 获取当前进程的内存使用
            process = psutil.Process(os.getpid())
            memory_info = process.memory_info()
            memory_mb = memory_info.rss / 1024 / 1024  # 转换为MB
            
            # 如果内存使用超过500MB，记录警告
            if memory_mb > 500:
                self.append_log(f"[内存警告] 当前内存使用: {memory_mb:.1f}MB")
                
                # 如果内存使用超过1GB，强制清理
                if memory_mb > 1024:
                    self.append_log("[内存警告] 内存使用过高，执行强制清理...")
                    self.force_memory_cleanup()
                    
        except ImportError:
            # 如果没有psutil模块，跳过内存监控
            pass
        except Exception as e:
            print(f"内存监控出错: {e}")
    
    def force_memory_cleanup(self):
        """强制内存清理"""
        try:
            import gc
            
            # 强制垃圾回收
            gc.collect()
            
            # 清理日志，只保留最近100行
            if hasattr(self, 'code_editor'):
                old = self.code_editor.toPlainText()
                lines = old.split('\n') if old else []
                if len(lines) > 100:
                    lines = lines[-100:]
                    self.code_editor.setPlainText('\n'.join(lines))
            
            self.append_log("[内存清理] 强制清理完成")
            
        except Exception as e:
            print(f"强制内存清理出错: {e}")

# 运行
if __name__ == '__main__':
    app = QApplication(sys.argv)
    # 设置全局样式
    app.setStyle('Fusion')

    # 设置调色板
    palette = QPalette()
    palette.setColor(QPalette.Window, QColor(240, 242, 245))  # 灰色背景
    palette.setColor(QPalette.WindowText, QColor(45, 55, 72))
    palette.setColor(QPalette.Base, QColor(255, 255, 255))
    palette.setColor(QPalette.AlternateBase, QColor(248, 250, 252))
    palette.setColor(QPalette.ToolTipBase, QColor(255, 255, 255))
    palette.setColor(QPalette.ToolTipText, QColor(45, 55, 72))
    palette.setColor(QPalette.Text, QColor(45, 55, 72))
    palette.setColor(QPalette.Button, QColor(45, 55, 72))  # 黑色按钮
    palette.setColor(QPalette.ButtonText, QColor(255, 255, 255))
    palette.setColor(QPalette.BrightText, QColor(255, 255, 255))
    palette.setColor(QPalette.Highlight, QColor(45, 55, 72))
    palette.setColor(QPalette.HighlightedText, QColor(255, 255, 255))
    app.setPalette(palette)

    window = QyhtThinkUI()
    window.show()
    sys.exit(app.exec_())